package cmd

import (
	"encoding/json"
	"fmt"
	"strings"

	"hal-client/client"

	"github.com/spf13/cobra"
)

// callCmd represents the call command
var callCmd = &cobra.Command{
	Use:   "call <method> [key=value...]",
	Short: "调用任意HAL方法",
	Long:  `调用任意HAL方法，支持传递键值对参数。`,
	Args:  cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		method := args[0]
		params := make(map[string]interface{})
		
		// 解析键值对参数
		for i := 1; i < len(args); i++ {
			parts := strings.SplitN(args[i], "=", 2)
			if len(parts) == 2 {
				params[parts[0]] = parts[1]
			}
		}
		
		resp, err := halClient.Request(method, params)
		if err != nil {
			fmt.Printf("请求失败: %v\n", err)
			return
		}
		printResponse(resp)
	},
}

// listCmd represents the list command
var listCmd = &cobra.Command{
	Use:   "list",
	Short: "列出可用的方法",
	Long:  `列出当前可用的HAL方法。`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("可用的Dummy模块方法:")
		fmt.Println("  dummy.hello     - 发送hello消息")
		fmt.Println("  dummy.counter   - 获取计数器值")
		fmt.Println("  dummy.echo      - 回显消息")
		fmt.Println("\n使用 'hal-cli call <method>' 调用任意方法")
	},
}

// printResponse 格式化并打印HAL响应
func printResponse(resp *client.HALResponse) {
	if resp.Error != nil {
		fmt.Printf("错误: [%d] %s\n", resp.Error.Code, resp.Error.Message)
		return
	}
	
	if resp.Result != nil {
		jsonData, err := json.MarshalIndent(resp.Result, "", "  ")
		if err != nil {
			fmt.Printf("响应: %+v\n", resp.Result)
		} else {
			fmt.Printf("响应:\n%s\n", string(jsonData))
		}
	} else {
		fmt.Println("响应: 成功")
	}
}

func init() {
	rootCmd.AddCommand(callCmd)
	rootCmd.AddCommand(listCmd)
}